import createApp from './app.js';
// https://webpack.js.org/guides/code-splitting-async/#dynamic-import-import-
import 'es6-promise/auto';
import Vue from 'Vue';

import { touchmove, touchend } from 'CommonDirective/touch';
Vue.use(touchmove);
Vue.use(touchend);

import Swipe from 'CommonDirective/swipe';
Vue.use(Swipe);

import infiniteScroll from 'vue-infinite-scroll';
Vue.use(infiniteScroll);

import ClickOutSide from 'CommonDirective/clickOutSide';
Vue.use(ClickOutSide);

import FastClick from 'fastclick';

if ('addEventListener' in document) {
	document.addEventListener('DOMContentLoaded', () => {
		FastClick.attach(document.body);
	}, false);
}

Vue.config.devtools = true;

Vue.mixin({
	// 在当前路由改变，但是该组件被复用时调用 http://router.vuejs.org/zh-cn/advanced/navigation-guards.html
	beforeRouteUpdate (to, from, next) {
		console.log(`client-beforeRouteUpdate`);
		let { asynData } = this.$options;
		if (asynData) {
			asynData({
				store: this.$store,
				router: to
			}).then(next).catch((err) => {
				console.log(err);
				next();
			});
		}
		else {
			next();
		}
	}
});

const { app, router, store } = createApp();

if (window.__INITIAL_STATE__) {
	store.replaceState(window.__INITIAL_STATE__);
}

router.onReady(() => {
	console.log(`client-onReady`);

	router.beforeResolve((to, from, next) => {
		console.log(`client-beforeResolve`);
		const matched = router.getMatchedComponents(to);
		const prevMatched = router.getMatchedComponents(from);
		let diffed = false;
		const activated = matched.filter((c, i) => {
			return diffed || (diffed = (prevMatched[i] !== c));
		});
		if (!activated.length) {
			return next();
		}
		Promise.all(activated.map((c) => {
			if (c.asyncData) {
				return c.asyncData({ store, route: to });
			}
		})).then(() => {
			next();
		}).catch(next);
	});
	app.$mount('#app');
});
